from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.urls import reverse

from django.utils import timezone

from account.models import User
from common.models import Common
from common.tools.common_tools import gen_id_number
from shop.models import ShopInfo


class Receiver(Common):
    """收货人信息"""
    user = models.ForeignKey(User, verbose_name=u'用户ID', null=True, blank=True, on_delete=models.SET_NULL)
    name = models.CharField(u'收货人姓名', max_length=30, default='')
    phone = models.CharField(u'收货人联系方式', max_length=11, default='')
    address = models.CharField(u'收货人地址', max_length=255, blank=True, default='')

    def __unicode__(self):
        return self.name

    class Meta:
        db_table = 'receiver'
        verbose_name = '收货人信息'


class Order(Common):
    """订单"""
    user = models.ForeignKey(User, verbose_name=u'用户ID', null=True, blank=True, on_delete=models.SET_NULL)
    superior = models.ForeignKey(User, verbose_name=u'来源用户', null=True, blank=True, related_name='order_from_user',
                                 help_text=u'该用户转发链接给当前下单用户', on_delete=models.SET_NULL)
    third_id = models.CharField(u'第三方支付订单ID', max_length=64, default='', null=True, blank=True)
    post_id = models.CharField(u'快递单号', max_length=64, default='', null=True, blank=True)
    shop = models.ForeignKey(ShopInfo, verbose_name=u'店铺', null=True,
                             on_delete=models.SET_NULL, related_name='order_shop')
    receiver = models.ForeignKey(Receiver, verbose_name=u'用户收货信息', null=True, blank=True, on_delete=models.SET_NULL)
    ORDER_PRODUCT, ORDER_SERVER, ORDER_CARD, ORDER_TUAN_MASTER = 1, 2, 3, 4
    ORDER_TUAN_GROUPER, ORDER_KILL, ORDER_KANJIA = 5, 6, 7
    ORDER_PIN_MASTER, ORDER_PIN_GROUP = 8, 9
    ORDER_TUANSHOPPING_MASTER, ORDER_TUANSHOPPING_GROUP = 10, 11
    ORDER_MORE_KAN, ORDER_HELP_KILL = 12, 13
    ORDER_KILL_DEPOSIT = 14
    ORDER_GROUP_SHOPPING_MASTER, ORDER_GROUP_SHOPPING_MEMBER = 15, 16
    SUPER_INITIAL, SUPER_JOIN = 17, 18
    ORDER_UNION_EXPAND = 19
    ORDER_TYPE = ((ORDER_PRODUCT, u'产品订单'), (ORDER_SERVER, u'项目订单'), (ORDER_CARD, u'卡项订单'),
                  (ORDER_TUAN_MASTER, u'开团订单'), (ORDER_TUAN_GROUPER, u'参团订单'),
                  (ORDER_KILL, u'秒杀订单'), (ORDER_KILL_DEPOSIT, u'秒杀定金订单'), (ORDER_KANJIA, u'砍价订单'),
                  (ORDER_PIN_MASTER, u'拼团开团'), (ORDER_PIN_GROUP, u'拼团参团'),
                  (ORDER_TUANSHOPPING_MASTER, u'团购开团'), (ORDER_TUANSHOPPING_GROUP, u'团购参团'),
                  (ORDER_MORE_KAN, u'多商品砍价'), (ORDER_HELP_KILL, u'助力秒杀'),
                  (ORDER_GROUP_SHOPPING_MASTER, u'新团购开团'), (ORDER_GROUP_SHOPPING_MEMBER, u"新团购参团"),
                  (ORDER_UNION_EXPAND, u'联盟拓客'), (SUPER_INITIAL, u'超拼开团'), (SUPER_JOIN, u"超拼参团"),)

    order_type = models.IntegerField(u'订单类型', choices=ORDER_TYPE, default=ORDER_PRODUCT, db_index=True)
    SELF_PUB, PAY_XIAODU, PAY_WX_SERVICE = 1, 2, 3
    PAY_TYPE = ((SELF_PUB, u'微信公众号支付'), (PAY_XIAODU, u'小嘟科技支付'), (PAY_WX_SERVICE, u'微信服务商子商户支付'),)
    pay_type = models.IntegerField(u'支付选择', choices=PAY_TYPE, default=PAY_XIAODU, blank=True)
    amount = models.IntegerField(u'总价(分)', default=0)
    refund = models.IntegerField(u'退款(分)', default=0)
    fact = models.IntegerField(u'实收(分)', default=0)

    STATE_WAIT_PAY = 1
    STATE_PAYED = 2
    STATE_SEND = 3
    STATE_COMPLETE = 4
    STATE_CANCELING = 5
    STATE_CANCELED = 6

    STATE_CLOSED = 7

    STATE_SYSTEM_CANCELING = 20
    STATE_SYSTEM_CANCELED = 21

    STATE = (
        (STATE_WAIT_PAY, u'待支付'),
        (STATE_PAYED, u'待发货'),
        (STATE_SEND, u'待收货'),
        (STATE_COMPLETE, u'已完成'),
        (STATE_CANCELING, u'取消中'),
        (STATE_CANCELED, u'已取消'),

        (STATE_CLOSED, u'已退款'),

        (STATE_SYSTEM_CANCELING, u'系统取消订单中'),
        (STATE_SYSTEM_CANCELED, u'系统取消订单'),
    )
    state = models.IntegerField(u'订单状态', choices=STATE, db_index=True)

    SOURCE_SHARE, SOURCE_SELF = 1, 2
    SOURCE_TYPE = ((SOURCE_SHARE, u'别人分享'), (SOURCE_SELF, u'自己购买'))
    source = models.IntegerField(u'订单来源', default=SOURCE_SHARE, choices=SOURCE_TYPE)

    payed_time = models.DateTimeField(u'支付完成时间', null=True, blank=True)
    send_time = models.DateTimeField(u'发货时间', null=True, blank=True)
    complete_time = models.DateTimeField(u'完成时间', null=True, blank=True)
    canceling_time = models.DateTimeField(u'订单取消时间', null=True, blank=True)
    canceled_time = models.DateTimeField(u'订单取消成功时间', null=True, blank=True)

    system_canceling_time = models.DateTimeField(u'系统取消订单时间', null=True, blank=True)
    system_canceled_time = models.DateTimeField(u'系统取消订单成功时间', null=True, blank=True)
    comment = models.CharField(u'订单备注', max_length=256, null=True, blank=True, default='')

    settle = models.BooleanField(u'是否结算', help_text=u'值为真时，不准退款', default=False, blank=True)
    chuang_split = models.BooleanField(u'是否创客分账', help_text=u'值为真时，不准退款', default=False)

    def __unicode__(self):
        return self.id

    class Meta:
        db_table = 'order'
        verbose_name = '订单'
        ordering = ['-create_time']


class OrderProduct(Common):
    """订单和产品"""
    order = models.ForeignKey(Order, verbose_name=u'订单ID', null=True,
                              on_delete=models.SET_NULL, related_name='op_order')
    object_id = models.CharField(u'业务id', max_length=30, default='', blank=True)
    content_type = models.ForeignKey(ContentType, null=True, blank=True, on_delete=models.SET_NULL)
    content_object = GenericForeignKey('content_type', 'object_id')

    price = models.IntegerField(u'单价(分)', default=0)
    number = models.IntegerField(u'数量', default=1)
    amount = models.IntegerField(u'总价(分)', default=0)
    refund = models.IntegerField(u'退款(分)', default=0)
    fact = models.IntegerField(u'实收(分)', default=0)
    OP_BUY, OP_GIFT = 1, 2
    OP_TYPE = ((OP_BUY, u'购买'), (OP_GIFT, u'赠送'))
    type = models.IntegerField(u'获取类型', choices=OP_TYPE, default=OP_BUY)

    def __unicode__(self):
        return self.id

    class Meta:
        db_table = 'order_product'
        verbose_name = '订单和产品'
        ordering = ['-create_time']


class RefundOrder(Common):
    """退款订单"""
    user = models.ForeignKey(User, verbose_name=u'用户ID', null=True, blank=True, on_delete=models.SET_NULL)
    order = models.ForeignKey(Order, verbose_name=u'购买订单ID', null=True,
                              on_delete=models.SET_NULL, related_name='refund_order')
    order_product = models.ForeignKey(OrderProduct, verbose_name=u'产品订单ID', null=True,
                                      on_delete=models.SET_NULL, related_name='refund_order_product')
    third_id = models.CharField(u'微信退款订单ID', max_length=64, default='', null=True, blank=True)
    shop = models.ForeignKey(ShopInfo, verbose_name=u'店铺', null=True,
                             on_delete=models.SET_NULL, related_name='refund_shop')
    money = models.IntegerField(u'待退款(分)', default=0)
    fact = models.IntegerField(u'实际退款(分)', default=0)

    object_id = models.CharField(u'业务id', max_length=30, default='', blank=True)
    content_type = models.ForeignKey(ContentType, null=True, blank=True, on_delete=models.SET_NULL)
    content_object = GenericForeignKey('content_type', 'object_id')

    STATE_WAIT_AGREE = 1
    STATE_AGREE = 2
    STATE_REFUNDING = 3
    STATE_REFUNDED = 4
    STATE_CANCELING = 5
    STATE_CANCELED = 6
    STATE_DENY = 7
    STATE_FAIL = 8

    STATE_SYSTEM_REFUNDING = 20
    STATE_SYSTEM_REFUNDED = 21

    STATE = (
        (STATE_WAIT_AGREE, u'等待商家同意退款申请'),
        (STATE_AGREE, u'商家同意退款'),
        (STATE_REFUNDING, u'退款中'),
        (STATE_REFUNDED, u'已退款'),
        (STATE_CANCELING, u'退款取消中'),
        (STATE_CANCELED, u'退款已取消'),
        (STATE_DENY, u'商家拒绝退款'),
        (STATE_FAIL, u'退款失败'),

        (STATE_SYSTEM_REFUNDING, u'系统退款中'),
        (STATE_SYSTEM_REFUNDED, u'系统退款完成'),
    )

    state = models.IntegerField(u'订单状态', choices=STATE, db_index=True)

    agree_time = models.DateTimeField(u'商家同意退款时间', null=True, blank=True)
    refunding_time = models.DateTimeField(u'退款开始时间', null=True, blank=True)
    refunded_time = models.DateTimeField(u'完成时间', null=True, blank=True)
    canceling_time = models.DateTimeField(u'订单取消时间', null=True, blank=True)
    canceled_time = models.DateTimeField(u'订单取消成功时间', null=True, blank=True)
    deny_time = models.DateTimeField(u'商家拒绝时间', null=True, blank=True)
    fail_time = models.DateTimeField(u'退款失败时间', null=True, blank=True)
    system_refunding_time = models.DateTimeField(u'系统发起退款时间', null=True, blank=True)
    system_refunded_time = models.DateTimeField(u'系统退款完成时间', null=True, blank=True)

    refund_reason = models.CharField(u'退款理由', max_length=256, default='', blank=True, help_text=u'用户填写的退款理由')
    deny_reason = models.CharField(u'拒绝理由', max_length=256, default='', blank=True, help_text=u'商家填写的拒绝退款理由')
    fail_reason = models.CharField(u'退款失败原因', max_length=256, default='', blank=True, help_text=u'微信支付返回的信息')

    def __unicode__(self):
        return self.id

    def save(self, *args, **kwargs):
        if not self.id:
            self.id = str(self.user_id) + timezone.now().strftime('%Y%m%d%H%M%S') + str(gen_id_number(4))
        return super(RefundOrder, self).save(*args, **kwargs)

    class Meta:
        db_table = 'refund_order'
        verbose_name = '退款订单'
        ordering = ['-create_time']
